package com.lizhenyao.waimai.service.impl;

import com.lizhenyao.waimai.dataobject.OrderMaster;
import com.lizhenyao.waimai.dto.OrderDTO;
import com.lizhenyao.waimai.enums.ResultEnum;
import com.lizhenyao.waimai.exception.SellException;
import com.lizhenyao.waimai.repository.OrderMasterRepository;
import com.lizhenyao.waimai.service.IBuyerService;
import com.lizhenyao.waimai.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: lizhenyao
 * @Desciption:
 */
@Service("IBuyerService")
@Slf4j
public class BuyerServiceImpl implements IBuyerService{

    @Autowired
    private IOrderService iOrderService;

    @Override
    public OrderDTO findOrderOne(String openid, String orderId) {
        OrderDTO orderDTO = checkOrderOwner(openid, orderId);
        if (orderDTO == null) return null;
        return orderDTO;
    }

    @Override
    public OrderDTO cancelOrder(String openid, String orderId) {
        OrderDTO orderDTO = checkOrderOwner(openid, orderId);
        if (orderDTO == null){
            log.error("[取消订单] 查不到该订单, orderId={}", orderId);
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        return iOrderService.cancel(orderDTO);
    }

    private OrderDTO checkOrderOwner(String openid, String orderId) {
        OrderDTO orderDTO = iOrderService.findOne(orderId);
        if (orderDTO == null){
            return null;
        }
        //判断是否为自己的订单
        if (!orderDTO.getBuyerOpenid().equalsIgnoreCase(openid)){
            log.error("[查询订单] 订单的openid不一致, openid={}, orderDTO={}", openid, orderDTO);
            throw new SellException(ResultEnum.ORDER_OWNER_ERROR);
        }
        return orderDTO;
    }
}
